package com.etc.controller;

import com.etc.dto.Result;
import com.etc.service.TencentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/code")
public class TencentController {

    @Autowired
    private TencentService tencentService;

    @Autowired
    private RedisTemplate<String,String > redisTemplate;

    @GetMapping("/send")
    public @ResponseBody Result send(@RequestParam String phone){
        Result result = new Result();
        //1.从redis获取验证码，若获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if (code!=null){
            result.ok(true);
            return result;
        }

        //redis中无验证码，调用业务发送短信
        boolean res = tencentService.send(phone);

        if(res){
            result.ok(true);
        }else {
            result.fail(0,"短信发送失败");
        }

        return result;
    }

    @GetMapping("/loginByCode")
    public @ResponseBody Result loginByCode(@RequestParam String phone,@RequestParam String code){
        Result result = new Result();

        //先检验是否发送了该手机号的验证码
        boolean codeExist = tencentService.codeExist(phone);
        if(!codeExist){
            result.fail(0,"请先点击发送验证码！");
            return result;
        }


        boolean flag = tencentService.loginByCode(phone, code);
        if(flag){
            result.ok(true);
        }else {
            result.fail(0,"验证码错误，登录失败");
        }
        return result;
    }

}
